﻿create PROCEDURE Sync.SP_UsersRoles_ApplyChanges
@RawValues XML 
AS 
BEGIN
	 
		DECLARE @UsersRoles_Temp TABLE 
		(
			RoleID UniqueIdentifier,
	UserID UniqueIdentifier,
			
			IsDeleted BIT, 
			LastUpdatedDate DATETIME
		)
		
	   INSERT INTO @UsersRoles_Temp 
	   SELECT	Tbl.Col.value('RoleID[1]','uniqueidentifier') RoleID,
Tbl.Col.value('UserID[1]','uniqueidentifier') UserID,
                
				Tbl.Col.value('IsDeleted[1]', 'bit') IsDeleted,
				Tbl.Col.value('LastUpdatedDate[1]','DateTime') LastUpdatedDate
	   FROM   @RawValues.nodes('/DocumentElement/UsersRoles') Tbl(Col)
----------------------------------------------------------------------------------------

-- Insert ------------------------------------------------------------------------------

	INSERT INTO [dbo].[UsersRoles] ([RoleID],[UserID])
	SELECT t.[RoleID],t.[UserID]
	FROM  @UsersRoles_Temp t
	WHERE t.IsDeleted = 0
    AND NOT EXISTS
    (
        SELECT 1 FROM sync.UsersRoles_Tracking s
        WHERE t.RoleID = s.RoleID AND t.UserID = s.UserID
    )
	-- put conflicts here.
	
-- Update -------------------------------------------------------------------------------
    -----------------------------------------------------------------------------------------

-- Delete -------------------------------------------------------------------------------

	DELETE [dbo].[UsersRoles]
    FROM @UsersRoles_Temp t JOIN [dbo].[UsersRoles] s
    ON t.RoleID = s.RoleID AND t.UserID = s.UserID
	WHERE t.IsDeleted = 1

-----------------------------------------------------------------------------------------
	
END














